package com.banciyuan.bcywebview.biz.follow;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.main.mineinfo.AddFriendsActivity;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.MineInfo;


public class FollowFragment extends BaseLazyContainerFragment implements View.OnClickListener {
    private String uid;
    private LoadingHelper mProgressbarHelper;
    private PullToRefreshListView listView;
    private int page = 1;
    private String type = "following";
    private boolean loading = false;
    private boolean end_flag = false;
    private RequestQueue mQueue;
    private List<MineInfo> list = new ArrayList<>();
    private boolean preLoad;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.activity_following, container, false);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        if (preLoad)
            initData(page);
        return viewroot;
    }

    @Override
    public void fetchData() {
        initData(page);
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
        Bundle bundle = getArguments();
        uid = StringUtil.getString(bundle, gotoUtil.INTENT_VALUE_ONE);
        preLoad = bundle.getBoolean("preLoad");
        type = StringUtil.getString(bundle, gotoUtil.INTENT_VALUE_TWO);
        if (TextUtils.isEmpty(type)) {
            type = "following";
        }
    }

    @Override
    protected void initProgressbar(View rootView) {
        if (StringUtil.notNullEqual(type, "follower")) {
            View fansView = rootView.findViewById(R.id.rl_fans_empty_view);
            mProgressbarHelper = new LoadingHelper(rootView, fansView);
        } else if (StringUtil.notNullEqual(type, "following")) {
            View followersView = rootView.findViewById(R.id.rl_followers_empty_view);
            mProgressbarHelper = new LoadingHelper(rootView, followersView);
        }
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                page = 1;
                initData(page);
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootView) {
        listView = (PullToRefreshListView) rootView.findViewById(R.id.lv);
        rootView.findViewById(R.id.tv_go_order_follow).setOnClickListener(this);
    }

    @Override
    protected void initAction() {
        listView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading) {
                    if (!end_flag) {
                        loading = true;
                        page++;
                        initData(page);
                    }
                }
            }
        });
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    loading = true;
                    end_flag = false;
                    page = 1;
                    initData(page);
                }
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position < 1) {
                    position = 1;
                }
                position = position - 1;
                MineInfo mineInfo = (MineInfo) adapter.getItem(position);
                if (null == mineInfo)
                    return;
                gotoUtil.gotoAct(getActivity(), SmoothPersonActivity.class, mineInfo.getUid());
            }
        });
    }


    protected void initData(final int page) {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        if (UserDataHelper.ifLogin(getActivity())) {
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
            paramsList.add(new BcyPair(HttpUtils.UID, uid));
            paramsList.add(new BcyPair(HttpUtils.TYPE, type));
            paramsList.add(new BcyPair(HttpUtils.LIMIT, "10"));
            paramsList.add(new BcyPair(HttpUtils.INDEX_P, "" + page));
        }
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + UserApi.getFollowlist();

        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    JSONObject result = null;
                    try {
                        result = new JSONObject(s);
                        Gson gson = new Gson();
                        List<MineInfo> templist = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<MineInfo>>() {
                        }.getType());
                        if (templist.isEmpty() && page == 1) {
                            mProgressbarHelper.onNodata("", true);
                            loading = false;
                            listView.onRefreshComplete();
                        } else if (templist.isEmpty()) {
                            end_flag = true;
                            loading = false;
                            mProgressbarHelper.onSuccess();
                            listView.onRefreshComplete();
                        } else {
                            processData(templist);
                        }
                        if ("follower".equals(type) && uid.equals(UserDataHelper.getInstance(getActivity()).getUid())) {
                            FlagUtils.newFansNum = 0;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        mProgressbarHelper.onFailed();
                        loading = false;
                        listView.onRefreshComplete();
                    }
                } else {
                    mProgressbarHelper.onFailed();
                    loading = false;
                    listView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                listView.onRefreshComplete();
                mProgressbarHelper.onFailed();
                loading = false;
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, getActivity(), params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private FollowAdapter adapter;

    private void processData(List<MineInfo> templist) {
        if (page == 1) {
            list.clear();
        }
        list.addAll(templist);
        if (null == adapter) {
            adapter = new FollowAdapter(getActivity(), list);
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        listView.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        loading = false;
    }

    public void doRemoveFans(boolean removeFansFlag) {
        adapter.setRemoveFlags(removeFansFlag);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_order_follow:
                gotoUtil.gotoAct(getActivity(), AddFriendsActivity.class);
                break;
        }
    }
}
